<?php
/**
 * Handles all calendar and event functions
 *
 *
 *  @author Jimmy E. Lewis
 *  @version 1.0
 */

class Calendar extends Controller{
	
	function __construct() {
		parent::__construct();
		$this->load->model('UserModel');
		$this->load->model('CalendarModel');
		$this->load->helper('date');
	}
	function index(){
		$this->full();
	}
	
	function withEvent(){
		if($this->validMonth($this->uri->segment(4))){
			$month = $this->uri->segment(4);
		}
		else{
			$month = date('n');
		}
		
		$day = 1;

		if($this->validYear($this->uri->segment(5))){
			$year = $this->uri->segment(5);
		}
		else{
			$year = date('Y');
		}
			$period = date("t",mktime(0,0,0,$month,1,$year));

		$start = mktime(0,0,0,$month,$day,$year);

		$dates = $this->_createCalendar($month,$day,$year);
		$a = 0;
		$b= $start;
		//get events for month
		while($a<$period){
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	

			$events = $this->CalendarModel->getEvents($start,$end);
			if($events->num_rows() > 0){
				foreach($events->result() as $row){
					$days[date("j",$start)][] = array(
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row->id
												);
				}


			}
			$a++;

		}
		if(isset($days)) $data = array( 'events' => $days, 'dates' => $dates, 'date' => $b); //if the month has events 
		else $data = array('dates' => $dates, 'date' => $b);
		$build = array('page'=>'full');
		$data = $data + $this->_buildContent($build);
		($this->uri->segment(6)=='cal_only') ? $data['cal_only'] = "yes" : $data['cal_only'] = 'no';
		/* for event */
		$data['id'] = $this->uri->segment(3);
		$event = $this->CalendarModel->getEvent($this->uri->segment(3));
		if($event!=null){
			$data = $data + array(
							'event' => $event, 
					);
			$data = $data + $this->_buildContent('none');
		
			$data['invited'] = false;
			if(isset($data['con_user'])){
				$userGroups = $this->UserModel->getGroupDescriptionsForUser($data['con_user']->userid);
				foreach($userGroups as $group){
					if($group==$event->category) $data['invited'] = true;
				}
				if($event->category=='XA') $data['invited'] = true;
			}
			if($data['invited']==true){
				$info = array('userid'=>$data['con_user']->userid, 'eventid'=>$this->uri->segment(3));
				$data['status'] = $this->CalendarModel->getRSVP($info,'status');
				if($data['status']!=null){
					if($data['status']->answer=='yes') $data['status'] = 'attending this event.';
					elseif($data['status']->answer=='no') $data['status'] = 'not attending this event.';
					else $data['status'] = 'maybe attending this event.';
				}
				else $data['status'] = 'not attending this event.';
			}
			if($data['event']->geocode!=""){
				$temp = explode(',',$data['event']->geocode);
				$data['event']->geocode = $temp[0];
				$data['event']->geocode2 = $temp[1];
			}
		}
		else $data['event'] = 'no';
		/* end for event */
		
		$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/styles.css" type="text/css" />'.PHP_EOL.
							'<link rel="stylesheet" href="'.base_url().'css/calendar.css" type="text/css" />'.PHP_EOL.
							'<link rel="stylesheet" href="'.base_url().'css/thickbox.css" type="text/css" media="screen" />'.PHP_EOL.
							'<script src="'.site_url("js/jquery.form.js").'" type="text/javascript"></script>'.PHP_EOL.
							'<script src="'.site_url("js/thickbox-compressed.js").'" type="text/javascript"></script>';
		$this->load->view('calendar/fullView',$data);
	}
	
	//---------------------- Function To Display Calendar ----------------------//
	
	/**
	 * Displays a full size calendar.
	 *
	 * @param int month -- sets the display month. Defaults to current month if not set.
	 * @param int year -- sets the display year.  Defaults to current year if not set.
	 * @param String 'cal_only' -- Only displays the html that makes up the calendar.  
	 *		 In order to use this you must enter a month and year also.
	 */
	function full(){
			if($this->validMonth($this->uri->segment(3))){
				$month = $this->uri->segment(3);
			}
			else{
				$month = date('n');
			}
			
			$day = 1;

			if($this->validYear($this->uri->segment(4))){
				$year = $this->uri->segment(4);
			}
			else{
				$year = date('Y');
			}
				$period = date("t",mktime(0,0,0,$month,1,$year));

			$start = mktime(0,0,0,$month,$day,$year);

			$dates = $this->_createCalendar($month,$day,$year);
			$a = 0;
			$b= $start;
			//get events for month
			while($a<$period){
				$start = mktime(0,0,0,$month,$day+$a,$year);
				$end = mktime(23,59,59,$month,$day+$a,$year);	

				$events = $this->CalendarModel->getEvents($start,$end);
				if($events->num_rows() > 0){
					foreach($events->result() as $row){
						$days[date("j",$start)][] = array(
														'start' => $row->start,
														'end' => $row->end,
														'name' => $row->name,
														'description' => $row->description,
														'location' => $row->location,
														'id' => $row->id
													);
					}


				}
				$a++;

			}
			if(isset($days)) $data = array( 'events' => $days, 'dates' => $dates, 'date' => $b); //if the month has events 
			else $data = array('dates' => $dates, 'date' => $b);
			$build = array('page'=>'full');
			$data = $data + $this->_buildContent($build);
			($this->uri->segment(5)=='cal_only') ? $data['cal_only'] = "yes" : $data['cal_only'] = 'no';
			$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/styles.css" type="text/css" />'.PHP_EOL.
								'<link rel="stylesheet" href="'.base_url().'css/calendar.css" type="text/css" />'.PHP_EOL.
								'<link rel="stylesheet" href="'.base_url().'css/thickbox.css" type="text/css" media="screen" />'.PHP_EOL.
								'<script src="'.site_url("js/jquery.form.js").'" type="text/javascript"></script>'.PHP_EOL.
								'<script src="'.site_url("js/thickbox-compressed.js").'" type="text/javascript"></script>';
			$this->load->view('calendar/fullView',$data);
	}
	
	/**
	 * Displays a full size calendar.
	 *
	 * @param int month -- sets the start month. Defaults to current month if not set.
	 * @param int day -- sets the start day.  Defaults to current day if not set.
	 * @param int year -- sets the start year.  Defaults to current year if not set.
	 * @param int period -- sets the number of days to get events for.  Defaults to 14.
	 *		 In order to use this you must enter a month, day, and year also.
	 */
	function agenda(){
		if($this->validMonth($this->uri->segment(3))){
			$month = $this->uri->segment(3);
		}
		else{
			$month = date('n');
		}
		if($this->validDay($this->uri->segment(4))){
			$day = $this->uri->segment(4);
		}
		else{
			$day = date('j');
		}
		if($this->validYear($this->uri->segment(5))){
			$year = $this->uri->segment(5);
		}
		else{
			$year = date('Y');
		}
		if($this->validPeriod($this->uri->segment(6))){
			$period = $this->uri->segment(6);
		}
		else{
			$period = 14;
		}
		$a = 0;
		while($a<=$period){
			
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	
			
			$events = $this->CalendarModel->getEvents($start,$end);
			if($events->num_rows() > 0){
				foreach($events->result() as $row){
					$days[date("Y-n-j",$start)][] = array(
													'date' => $start,
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row
												);
				}
				
			
			}
			$a = $a + 1;
			
		}
		

		if(isset($days)) $data = array( 'events' => $days);
//		$data = $data + $this->_buildContent();
		(isset($days)) ? $this->load->view('calendar/listView',$data) : $this->load->view('calendar/listView');
	}
	
	/**
	 * Displays the next seven days.
	 */
	function week(){
		$month = date('n');
		$day = date('j');
		$year = date('Y');
				
		$period = 7;

		$a = 0;
		while($a<$period){
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	
			
			$events = $this->CalendarModel->getEvents($start,$end);
			
			if($events->num_rows() > 0){
//				echo "<br>" . $events->num_rows();
				foreach($events->result() as $row){
					$days[date("Y-n-j",$start)][] = array(
													'date' => $start,
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row
												);
				}
				
			
			}
			$a++;
			
		}
		
		$dates = $this->_createWeekly($month,$day,$year,"7");
		
		if(isset($days)) $data = array( 'events' => $days, 'week' => $dates['dates'], 'dayOrder' => $dates['dayOrder']);
		else $data = array('week' => $dates['dates'], 'dayOrder' => $dates['dayOrder']);

		$this->load->view('calendar/weekView',$data);
	}
	
	//---------------------- Functions Make Calendar ----------------------//
	
	/**
	 * Creates the arrays for a weekly calendar.  Sets both the day names and numbers.
	 */
	function _createWeekly($month,$day,$year,$period){
		$start = mktime(0,0,0,$month,$day,$year);
		$a = 0;
		while($a<$period){
			$dayOrder[] = date("l",strtotime("+$a days",$start));
			$dates[] = date("Y-n-j",strtotime("+$a days",$start));
			$a++;
		}
		$data = array('dates' => $dates, 'dayOrder' => $dayOrder);
		return $data;
	}

	/**
	 * Creates the arrays for a full calendar.
	 */
	function _createCalendar($month,$day,$year){
		$date = mktime(0,0,0,$month,1,$year);
		$daysInMonth = date("t",mktime(0,0,0,$month,1,$year));
		$firstDay = date("w",mktime(0,0,0,$month,1,$year));

		$tempDays = $firstDay + $daysInMonth;
		$weeksInMonth = ceil($tempDays/7);


		$counter = 0;

		for($j=0;$j<$weeksInMonth;$j++) {
			for($i=0;$i<7;$i++) {
				$counter++;
				$week[$j][$i] = $counter;
				// offset the days
				$week[$j][$i] -= $firstDay;
				if (($week[$j][$i] < 1) || ($week[$j][$i] > $daysInMonth)) {    
					$week[$j][$i] = "";
				}
			}
		}
		return $week;
		
	}
	
	//---------------------- Functions For Items ----------------------//
	
	function assignItem(){
		$id = $this->uri->segment(3);
		$item = $this->CalendarModel->getItem($id);
		//Has this item aready been assigned?
		if($item->assign==""){
			$post['assign'] = $this->uri->segment(4);
			$this->CalendarModel->assignItem($id,$post);
		}
		$event = $this->CalendarModel->getEventForItem($id);
		$event->month = date("n",strtotime($event->start));
		$event->year = date("n",strtotime($event->start));
		redirect("calendar/calendar1/$event->month/$event->year/$event->id");
	}
	
	/**
	 * Displays page: This is the write page for composing an item
	 */
	function createItem(){
		$this->badger->checkAllow('admin staff xalt');
		$build = array('page'=>'createItem');
		$data = $this->_buildContent($build);
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'name';
		$fields['event_id']	= 'event_id';
		$fields['redirect'] = 'redirect';
		
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$this->load->view('calendar/createItem',$data);
		} else {
			$post['name'] = $this->input->post('name',TRUE);
			$post['event_id'] = $this->input->post('event_id',TRUE);

			$this->CalendarModel->createItem($post);
			//if($this->input->post('redirect')=='admin') redirect('admin/events');
			//else redirect("calendar/eventDetails/$post[event_id]");
		}
	}
	
	/**
	 * Displays page to allow editing an item.  The editor must be an admin, xalt, of staff member
	 */
	function editItem(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$data['event'] = $this->CalendarModel->getEvent($this->uri->segment(3));
		$data = $data + $this->_buildContent();
		$this->load->view('calendar/item_edit', $data);
	
	}
	
	/**
	 * Displays page to allow deleting an item.  The deleter must be an admin, xalt, of staff member
	 */
	function deleteItem(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$this->CalendarModel->deleteItem($this->uri->segment(3));
		$data['admin'] = $this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'));
		if($data['admin']) redirect('admin/events');
		else redirect('calendar/full');
		
	}
	
	/**
	 * Displays the items for an event
	 */
	function event_items(){
		$this->badger->checkAllow('admin');
		$items = $this->CalendarModel->getItems($this->uri->segment(3));
		foreach($items->result() as $row) {
			if($row->assign!=""){
				$row->author = $this->UserModel->getUsername($row->assign);
				$row->authorname = $this->UserModel->getDisplayName($row->assign);
			}
		}
		$data['items'] = $items;
		$data['event'] = $this->uri->segment(3);
		$build = array('page'=>'eventItems');
		$data = $data + $this->_buildContent($build);
		$data['pagetype'] = 'page_admin';
		$data['admin_nav'] = TRUE;
		$this->load->view('calendar/eventItems', $data);
	}
	
	//---------------------- Functions For Events ----------------------//
	
	
	/**
	 * Displays page: This is the write page for composing a event
	 */
	function create(){
		$this->badger->checkAllow('admin staff xalt');
		$build = array('page'=>'createEvent');
		$data = $this->_buildContent($build);
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['description'] = "trim|required|required";
		$rules['start'] = "trim|required";
		$rules['end'] = "trim|required";
		$rules['status'] = "callback_status_check";
		
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'name';
		$fields['description']	= 'description';
		$fields['repeating']	= 'repeating';
		$fields['repeating_end'] = 'repeating_end';
		$fields['start']	= 'start';
		$fields['start_time_hour'] = 'start_time_hour';
		$fields['start_time_mins'] = 'start_time_mins';
		$fields['start_time_half'] = 'start_time_half';
		$fields['end']	= 'end';
		$fields['end_time_hour'] = 'end_time_hour';
		$fields['end_time_mins'] = 'end_time_mins';
		$fields['end_time_half'] = 'end_time_half';
		$fields['homepage'] = 'homepage';
		$fields['street'] = 'street';
		$fields['city'] = 'city';
		$fields['state'] = 'state';
		$fields['geocode_point'] = 'geocode_point';
		$fields['status'] = 'status';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$this->load->view('calendar/createEvent',$data);
		}
		else {
			if($this->input->post('repeating')=="no"){
				$post['name'] = $this->input->post('name',TRUE);
				$post['description'] = $this->input->post('description',TRUE);
				$startHour = $this->input->post('start_time_hour');
				$startMin = $this->input->post('start_time_mins');
				$startHalf = $this->input->post('start_time_half');
				$endHour = $this->input->post('end_time_hour');
				$endMin = $this->input->post('end_time_mins');
				$endHalf = $this->input->post('end_time_half');
				$startTime = date("G:i:s", strtotime("$startHour:$startMin $startHalf "));
				$endTime = date("G:i:s", strtotime("$endHour:$endMin $endHalf "));
				$post['start'] = $this->input->post('start',TRUE) . ' ' . $startTime;
				$post['end'] = $this->input->post('end',TRUE) . ' ' . $endTime;
				$post['street'] = $this->input->post('street');
				$post['city'] = $this->input->post('city');
				$post['state'] = $this->input->post('state');
				$post['homepage'] = $this->input->post('homepage');
				$post['geocode'] = $this->input->post('geocode_point');
				$this->CalendarModel->createEvent($post);
			}
			else{
				if($this->input->post('repeating')=="weekly"){
					$random = substr($this->input->post('name'),0,10) . time();
					$startHour = $this->input->post('start_time_hour');
					$startMin = $this->input->post('start_time_mins');
					$startHalf = $this->input->post('start_time_half');
					$endHour = $this->input->post('end_time_hour');
					$endMin = $this->input->post('end_time_mins');
					$endHalf = $this->input->post('end_time_half');
					$start = $this->input->post('start');
					$end = $this->input->post('end');
					if($this->input->post('repeating')=='weekly') $repeat = "+1 week";
					$start = $this->input->post('start',TRUE);
					$end = $this->input->post('end',TRUE);
					$repeating_end = strtotime($this->input->post('repeating_end',TRUE));
					do{
						$startHour = $this->input->post('start_time_hour');
						$startMin = $this->input->post('start_time_mins');
						$startHalf = $this->input->post('start_time_half');
						$endHour = $this->input->post('end_time_hour');
						$endMin = $this->input->post('end_time_mins');
						$endHalf = $this->input->post('end_time_half');
						$post['name'] = $this->input->post('name',TRUE);
						$post['description'] = $this->input->post('description',TRUE);
						$startHour = $this->input->post('start_time_hour');
						$startMin = $this->input->post('start_time_mins');
						$startHalf = $this->input->post('start_time_half');
						$endHour = $this->input->post('end_time_hour');
						$endMin = $this->input->post('end_time_mins');
						$endHalf = $this->input->post('end_time_half');
						$startTime = date("G:i:s", strtotime("$startHour:$startMin $startHalf "));
						$endTime = date("G:i:s", strtotime("$endHour:$endMin $endHalf "));
						$post['start'] = $start . ' ' . $startTime;
						$post['end'] = $end . ' ' . $endTime;
						$post['street'] = $this->input->post('street');
						$post['city'] = $this->input->post('city');
						$post['state'] = $this->input->post('state');
						$post['homepage'] = $this->input->post('homepage');
						$post['geocode'] = $this->input->post('geocode_point');
						$post['repeating_id'] = $random;
						$post['repeating_type'] = $this->input->post('repeating');
						$this->CalendarModel->createEvent($post);
						$continue = strtotime($repeat,strtotime($start));
						$start = date("Y-m-d",strtotime($repeat,strtotime($start)));
						$end = date("Y-m-d",strtotime($repeat,strtotime($end)));
					} while($continue<=$repeating_end);
				}
			}
			if($data['admin']) redirect('admin/events');
			else redirect('calendar/full');
		}
	}
	
	function status_check($status)
		{
			if($status=='200'){
				return true;
			}
			else{
				$this->validation->set_message('status_check', 'Google Maps was unable to understand your address');
				return false;
			}
		}
	
	function deleteEvent(){
		$this->badger->checkAllow('admin staff xalt');
		
		$rules['id'] = "trim";
		$rules['redirect'] = "trim";
		$this->load->library('validation');
		$this->validation->set_rules($rules);
		
		$fields['id'] = 'id';
		$fields['redirect'] = 'redirect';
		
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		if($this->validation->run() == FALSE) {
			$data['id'] = $this->uri->segment(3);
			$event = $this->CalendarModel->getEvent($data['id']);
			$data['repeating_id'] = $event->repeating_id;
			$data['redirect'] = $this->uri->segment(2);
			$data['admin'] = $this->uri->segment(4);
			$this->load->view('calendar/deleteEvent',$data);
		}
		else{
			$admin = $this->input->post('admin');
			$redirect = $this->input->post('redirect');
			$id = $this->input->post('id');
			if($redirect=='' || 'withEvent') $redirect = 'withEvent';
			else $redirect = 'eventDetails';
			if($this->input->post('submit')!='Cancel'){
				$delete = $this->input->post('submit');
				
				if($delete=='Yes'){
					$this->CalendarModel->deleteEvent($id); //not a repeating event so just delete
					if($admin=='admin') redirect("admin/events");
					else redirect("calendar/$redirect/$id");
				}
				else if($delete=='Delete This Only'){
					$this->CalendarModel->deleteEvent($id); //delete only this event
					if($admin=='admin') redirect("admin/events");
					else redirect('calendar');
				}
				else{
					$this->CalendarModel->deleteRepeating($this->input->post('repeating_id'));
					if($admin=='admin') redirect("admin/events");
					else redirect('calendar');
				}
			}
			else{
				if($admin=='admin') redirect("admin/events");
				else redirect("calendar/$redirect/$id");
			}
		}

	}
	
	
	/**
	 * Displays page to allow editing an event.  The editor must be an admin, xalt, of staff member
	 */
	function editEvent(){
		$this->badger->checkAllow('admin staff xalt');
		$data['event'] = $this->CalendarModel->getEvent($this->uri->segment(3));
		$data['admin'] = $this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'));
		$build = array('page'=>'createEvent');
		$data = $data + $this->_buildContent($build);
		$data = $data + array(
							'startHour'=> date("g",strtotime($data["event"]->start)),
							'startMin'=>  date("i",strtotime($data["event"]->start)),
							'startHalf'=>  date("a",strtotime($data["event"]->start)),
							'endHour'=> date("g",strtotime($data["event"]->end)),
							'endMin'=> date("i",strtotime($data["event"]->end)),
							'endHalf'=> date("a",strtotime($data["event"]->end)),
							
							);
		$this->load->view('calendar/event_edit', $data);
	
	}
	
	/**
	 * Edits a post with submitted information
	 */
	function doEditPost() {
		//needs valadation 
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$post['name'] = $this->input->post('name', TRUE);
		$post['description'] = $this->input->post('description', TRUE);
		$startHour = $this->input->post('start_time_hour');
		$startMin = $this->input->post('start_time_mins');
		$startHalf = $this->input->post('start_time_half');
		$endHour = $this->input->post('end_time_hour');
		$endMin = $this->input->post('end_time_mins');
		$endHalf = $this->input->post('end_time_half');
		$startTime = date("G:i:s", strtotime("$startHour:$startMin $startHalf "));
		$endTime = date("G:i:s", strtotime("$endHour:$endMin $endHalf "));
		$post['start'] = $this->input->post('start',TRUE) . ' ' . $startTime;
		$post['end'] = $this->input->post('end', TRUE) . ' ' . $endTime;
		$post['state'] = $this->input->post('state');
		$post['city'] =  $this->input->post('city');
		$post['street'] = $this->input->post('street');
		$post['geocode'] = $this->input->post('geocode_point');
//		$post['category'] = $this->input->post('category');
		$post['homepage'] = $this->input->post('homepage');
		$post['category'] = 'XA';
		$id = $this->input->post('id');
			
		$this->load->model('CalendarModel');
		$this->CalendarModel->updateEvent($id,$post);
		
		if($this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'))) redirect('admin/events');
		else redirect('calendar/full');
	}
	
	/*
	 * Displays and event
	 */
	function event($id){
		$event = $this->CalendarModel->getEvent($id);
		if($event!=null){
			$data = array(
							'event' => $event, 
					);
			$data = $data + $this->_buildContent('none');
		
			$data['invited'] = false;
			if(isset($data['con_user'])){
				$userGroups = $this->UserModel->getGroupDescriptionsForUser($data['con_user']->userid);
				foreach($userGroups as $group){
					if($group==$event->category) $data['invited'] = true;
				}
				if($event->category=='XA') $data['invited'] = true;
			}
			if($data['invited']==true){
				$info = array('userid'=>$data['con_user']->userid, 'eventid'=>$id);
				$data['status'] = $this->CalendarModel->getRSVP($info,'status');
				if($data['status']!=null){
					if($data['status']->answer=='yes') $data['status'] = 'attending this event.';
					elseif($data['status']->answer=='no') $data['status'] = 'not attending this event.';
					else $data['status'] = 'maybe attending this event.';
				}
				else $data['status'] = 'not attending this event.';
			}
			if($data['event']->geocode!=""){
				$temp = explode(',',$data['event']->geocode);
				$data['event']->geocode = $temp[0];
				$data['event']->geocode2 = $temp[1];
			}
			$this->load->view('calendar/eventView',$data);
		}
		else return "";
	}
	
	function eventDetails($id){
		$event = $this->CalendarModel->getEvent($id);
		if($event!=null){ //Is this event a valid event
			$items = $this->CalendarModel->getItems($id);
			$coming = $this->CalendarModel->getRSVP($id,'yes');
			$notComing = $this->CalendarModel->getRSVP($id,'no');
			$maybeComing = $this->CalendarModel->getRSVP($id,'maybe');
			foreach ($coming->result() as $row) {
				$row->author = $this->UserModel->getDisplayName($row->user_id);
			}
			foreach ($notComing->result() as $row) {
				$row->author = $this->UserModel->getDisplayName($row->user_id);
			}
			foreach ($maybeComing->result() as $row) {
				$row->author = $this->UserModel->getDisplayName($row->user_id);
			}

			$data = array(
							'event' => $event,
							'items' => $items,
							'coming' => $coming,
							'notComing' => $notComing,
							'maybeComing' => $maybeComing
					);
		
			$build['id'] = $id;
			$build['page'] = 'eventDetails';
			$data = $data + $this->_buildContent($build);
			$data['invited'] = false;
			if(isset($data['con_user'])){
				$userGroups = $this->UserModel->getGroupDescriptionsForUser($data['con_user']->userid);
				foreach($userGroups as $group){
					if($group==$event->category) $data['invited'] = true;
				}
				if($event->category=='XA') $data['invited'] = true;
			}
			if($data['invited']==true){
				$info = array('userid'=>$data['con_user']->userid, 'eventid'=>$id);
				$data['status'] = $this->CalendarModel->getRSVP($info,'status');
				if($data['status']!=null){
					if($data['status']->answer=='yes') $data['status'] = 'attending this event.';
					elseif($data['status']->answer=='no') $data['status'] = 'not attending this event.';
					else $data['status'] = 'maybe attending this event.';
				}
				else $data['status'] = 'not attending this event.';
			}
			if($data['event']->geocode!=""){
				$temp = explode(',',$data['event']->geocode);
				$data['event']->geocode = $temp[0];
				$data['event']->geocode2 = $temp[1];
			}
			$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/styles.css" type="text/css" />'.PHP_EOL.
								'<link rel="stylesheet" href="'.base_url().'css/calendar.css" type="text/css" />'.PHP_EOL.
								'<link rel="stylesheet" href="'.base_url().'css/thickbox.css" type="text/css" media="screen" />'.PHP_EOL.
								'<script src="'.site_url("js/jquery.form.js").'" type="text/javascript"></script>'.PHP_EOL.
								'<script src="'.site_url("js/thickbox-compressed.js").'" type="text/javascript"></script>';
		
		$data['pagetype'] = 'nobg';
		$this->load->view('calendar/eventDetailsView',$data);
		}
		else redirect('calendar'); //if not valid redirect to main calendar
	}
	
	function rsvp(){
		$data = $this->_buildContent("rsvp");
		if(isset($data['con_user'])){
			$userGroups = $this->UserModel->getGroupDescriptionsForUser($data['con_user']->userid);
			$event = $this->CalendarModel->getEvent($this->uri->segment(3));
			if($event!=null){
				foreach($userGroups as $group){
					if($group==$event->category) $data['invited'] = true;
				}
				if($event->category=='XA') $data['invited'] = true;
		
				if($data['invited']==true){
					$data['event'] = $this->uri->segment(3);
					$this->load->view('calendar/rsvp',$data);
				}
				 //can't rsvp to an event you're not invited to
			}
 //can't rsvp to an invalid event
		}
 //can't rvsp if you no a user
	}
	
	function dorsvp(){
		$data = $this->_buildContent("rsvp");
		if(isset($data['con_user'])){
			$userGroups = $this->UserModel->getGroupDescriptionsForUser($data['con_user']->userid);
			$event = $this->CalendarModel->getEvent($this->input->post('event'));
			if($event!=null){
				foreach($userGroups as $group){
					if($group==$event->category) $data['invited'] = true;
				}
				if($event->category=='XA') $data['invited'] = true;
		
				if($data['invited']==true){
					$info = array('userid'=>$data['con_user']->userid, 'eventid'=>$this->input->post('event'));
					$data['status'] = $this->CalendarModel->getRSVP($info,'status');
				
					$a = strtolower($this->input->post('submit'));
					$this->session->set_flashdata('msg_info',"You RSVP has been changed to $a");
				
					if($data['status']!=null){ //user wants to change rsvp
						if($this->input->post('submit')=='Attending') $post = array('answer' => 'yes');
						else if($this->input->post('submit')=='Maybe Attending') $post = array('answer' => 'maybe');
						else $post = array('answer' => 'no');
					
						$data['event_id'] = $this->input->post('event');
						$data['user_id'] = $data['con_user']->userid;
					
						$this->load->model('CalendarModel');
						$this->CalendarModel->updateRSVP($data,$post);
						echo "<script type=\"text/javascript\">
						parent.thickboxDone();
						</script>";
					} else{ //user wants to rsvp
						if($this->input->post('submit')=='Attending') $post['answer'] = 'yes';
						else if($this->input->post('submit')=='Maybe Attending') $post['answer'] = 'maybe';
						else $post['answer'] = 'no';
					
						$post['event_id'] = $this->input->post('event');
						$post['user_id'] = $data['con_user']->userid;
					
						$this->load->model('CalendarModel');
						$this->CalendarModel->createRSVP($post);
						echo "hey<script type=\"text/javascript\">
						parent.thickboxDone();
						</script>";
					
					}
				}
			}
		//can't rsvp to invaild event
			
		}
		//else //redirect
		
		
		
		
		
	}
	
	function map(){
		$data['geocode'] = $this->uri->segment(3) . ',' . $this->uri->segment(4);
		$this->load->view('calendar/map',$data);
	}
	
	//check event id
	function sidebar(){
		$id = $this->uri->segment(3);
		if($id!='none') $build = array('page'=>'sidebar','id'=>$id);
		else $build['page'] = 'none';
		$data = $this->_buildContent($build);
		$this->load->view('calendar/sidebar',$data);
	}
	
	function validMonth($month){
		if($month!='' && is_numeric($month) && $month>=1 && $month<=12){
			return true;
		}

		return false;
	}
	
	function validDay($day){
		if($day!='' && is_numeric($day) && $day>=1 && $day<=31){
			return true;
		}

		return false;
	}
	
	function validYear($year){
		if($year!='' && is_numeric($year) && strlen($year)==4 && $year>=1970 && $year<=2032){
			return true;
		}

		return false;
	}
	
	function validPeriod($period){
		if($period!='' && is_numeric($period) && $period>=1){
			return true;
		}

		return false;
	}
	/*
	 * Supplies user-specific information to the interface for customization
	 */
	function _buildContent($temp) {
		if ($this->session->userdata('loggedin')) {
			$admin = $this->UserModel->isUserInGroup($this->UserModel->getUserByName($this->session->userdata('username'))->userid,$this->UserModel->getGroupID('admin'));
			$xalt = $this->UserModel->isUserInGroup($this->UserModel->getUserByName($this->session->userdata('username'))->userid,$this->UserModel->getGroupID('xalt'));
		} else{
			$admin = false;
			$xalt = false;
		}
		//REQUIRED//
		
		/**
		 *Page Type & side bar display
		 */
		if($this->session->userdata('loggedin')){
			if($temp['page']!='createEvent' && $admin!=true) $data['sidebar'] = true;
			elseif($temp['page']=="full" || $temp['page']=='eventDetails') $data['sidebar'] = true;
		}
		if($admin && $temp['page']=='createEvent'){
			$data['pagetype'] = 'page_admin';
			$data['admin_nav'] = true;
			$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/admin.css" type="text/css" />';
		}
		if($temp['page']=='fullCalendar'){
			$data['pagetype'] = 'nobg';
		}
		
		
		
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');
		if ($this->session->flashdata('msg_error')) $data['msg_error'] = $this->session->flashdata('msg_error');
		
		//test if user is logged in for site navigation
		if ($this->session->userdata('loggedin')) {
			$data['loggedin'] = TRUE;
			//grab the user
			$user = $this->UserModel->getUserByName($this->session->userdata('username'));
			$user->display = $this->UserModel->getDisplayName($user->userid);
		

			//is admin?
			if ($admin) {
				$data['admin_tab'] = TRUE;
				$data['links'] = '<a href="'.site_url("site/logout").'">logout</a>';
				$data['page_info']['title'] = 'calendar';
				$data['page_info']['items'][] = anchor('calendar/create', 'Create a calendar event');
				if($temp['page']=="sidebar"){ $data['page_info']['items'][] = "<a href=\"" . site_url("calendar/deleteEvent/$temp[id]/sidebar/") . "\"  title=\"Delete an Event\" class=\"thickbox\" id=\"deleteEvent\">Delete this event</a>";
				}
				else if($temp['page']=='eventDetails'){
					$data['page_info']['items'][] = anchor("calendar/editEvent/$temp[id]", 'Edit this event');
					$data['page_info']['items'][] = "<a href=\"" . site_url("calendar/deleteEvent/$temp[id]/sidebar/") . "\"  title=\"Delete an Event\" class=\"thickbox\" id=\"deleteEvent\">Delete this event</a>";
					$data['page_info']['items'][] = "<a href=\"" . site_url("calendar/createItem/$temp[id]/sidebar/") . "\"  title=\"Add an Item\" class=\"thickbox\" id=\"item\">Add an item to this event</a>";
					$data['page_info']['items'][] = "<a href=\"" . site_url("calendar/rsvp/$temp[id]/") . "\" title=\"Change RSVP To\" class=\"thickbox\" id=\"rsvp\">Change RSVP status</a>";
				}
			}			
			//is xalt?
			elseif($xalt) {
				$data['links'] = '<a href="'.site_url("site/logout").'">logout</a>';
				$data['page_info']['title'] = 'calendar';
				if($temp['type']!='eventDetails') $data['page_info']['items'] = array(anchor('calendar/create', 'Compose an event entry'));
				if($temp['type']=='eventDetails'){
					$data['page_info']['items'][] = anchor('calendar/create', 'Create a calendar this event');
					$data['page_info']['items'][] = anchor("calendar/delete/$temp[id]", 'Delete this event');
				}
				
			}
			else{  //needs validation that user is in event group
				$data['links'] = '<a href="'.site_url("site/logout").'">logout</a>';
				$data['page_info']['title'] = 'calendar';
				$data['page_info']['items'][] = anchor("calendar/rsvp/$temp[id]/$user->userid",'Change RSVP status');
			}
			
			$data['con_user'] = $user;
		}
		
		$data['admin'] = $admin;
		$data['xalt'] = $xalt;
		
		return $data;
	}
	
	/*
	 * Admin: Supplies user-specific information to the interface for customization
	 */
	function _buildAdminContent() {
		//REQUIRED//
		$data['pagetype'] = 'page-admin';
		$data['admin_nav'] = TRUE;
		$data['admin'] = true;
		
		return $data;
	}
}
?>
